package controllers

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/sessions"
	"strings"
)

type ThumbsUp struct {
	Ctx iris.Context
}

// 给某条说说点赞
func (c *ThumbsUp) PostCreate() interface{} {
	channel := c.Ctx.PostValue("channel")
	trendsId := utils.Atoi64(c.Ctx.PostValueDefault("trendsId", "0"))

	if len(channel) <= 0 {
		return utils.CommonRes(1000, "请提供渠道", "")
	}
	if trendsId <= 0 {
		return utils.CommonRes(1000, "请提供说说id", "")
	}

	var userId int64
	if strings.EqualFold(channel, "wechat") {
		token := c.Ctx.GetHeader("token")
		claims, err := utils.ParseToken(token)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("解析token出错：%s", err.Error()), "")
		}
		userId = utils.Atoi64(claims.Id)
	} else {
		session := sessions.Get(c.Ctx)
		userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	ok, err := db.Table(new(models.ThumbsUp)).Where("user_id = ? and trends_id = ?", userId, trendsId).Exist()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}
	if ok {
		return utils.CommonRes(1000, "您已点过赞了", "")
	}

	newThumbsUp := new(models.ThumbsUp)
	newThumbsUp.UserId = userId
	newThumbsUp.TrendsId = trendsId
	_, err = db.InsertOne(newThumbsUp)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("点赞失败：%s", err.Error()), "")
	}

	trends := new(models.Trends)
	_, err = db.ID(trendsId).Get(trends)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("点赞失败：%s", err.Error()), "")
	}

	updateData := map[string]interface{}{
		"up_num": trends.UpNum + 1,
	}
	db.Table(new(models.Trends)).ID(trendsId).Update(updateData)

	thumbsUp := new(models.ThumbsUpObj)
	_, err = db.Table(new(models.ThumbsUp)).Alias("tu").
		Join("INNER", []string{"user", "u"}, "tu.user_id = u.id").
		Where("tu.id = ?", newThumbsUp.Id).Get(thumbsUp)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("点赞失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "点赞成功", thumbsUp)
}
